package image.util;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by IntelliJ IDEA.
 * User: localadmin
 * Date: 13.01.2011
 * Time: 15:15:05
 */
public class JSmoothProgressBar extends JProgressBar {
    private static final double WEIGHT_AVG = 0.3;
    private static final double WEIGHT_LAST = 0.68;
    private static final int TIME = 200;
    private long lastSetTime;
    private int avg;
    private Timer timer;

    class TimerListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (getValue() >= getMaximum()) {
                timer.stop();
            } else {
                setRealValue(getValue() + 1);
            }
        }
    }

    public JSmoothProgressBar(int min, int max) {
        super(min, max);
        timer = new Timer(10, new TimerListener());
    }

    public void setValue(int value) {
        int current = getValue();
        int diff = value - current;
        
        if (diff > 1 && current != value) {
            int time = (int) (lastSetTime == 0 ? TIME : (System.currentTimeMillis() - lastSetTime));
            avg = (int) (avg == 0 ? time : avg * WEIGHT_AVG + time * WEIGHT_LAST);
            int delay = (avg / diff);
            timer.stop();
            timer.setDelay(delay);
            timer.restart();
        } else {
            setRealValue(value);
        }
        lastSetTime = System.currentTimeMillis();
    }

    private void setRealValue(int value) {
        super.setValue(value);
    }
}
